class Solution {

    class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        if (k==1 || head.next == null) {
            return head;
        }
        ListNode dummy = new ListNode(0, head);
        ListNode start = dummy, tail = start;
        while (tail != null){
            int cnt = 0;
            while (cnt < k && tail.next != null) {
                cnt++;
                tail = tail.next;
            }
            if (cnt < k) {
                return dummy.next;
            } else {
                ListNode p = start.next, q = p.next, r = q.next;
                while (p != tail) {         
                    q.next = p;
                    p = q;
                    q = r;
                    if (r != null) {
                        r = r.next;
                    }
                }
                tail = start.next;
                start.next = p;
                tail.next = q;
            }
            start = tail;
            tail = start;
        }
        return dummy.next;
    }
}